package cn.dubito.miaosha.exception.handler;

import cn.dubito.miaosha.controller.vo.CodeMsg;
import cn.dubito.miaosha.controller.vo.Result;
import cn.dubito.miaosha.exception.SeckillException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author liliang
 * @description: 异常处理器
 * @date 2018/3/31.
 */
@ControllerAdvice
@ResponseBody
public class SeckillExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(SeckillExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e) {
        if (e instanceof SeckillException) {
            logger.error(e.getMessage());
            SeckillException se = (SeckillException) e;
            return Result.error(se.getCodeMsg());
        } else if (e instanceof BindException) {
            logger.error(e.getMessage());
            BindException be = (BindException) e;
            List<ObjectError> errors = be.getAllErrors();
            String message = errors.get(0).getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(message));
        } else {
            logger.error(e.getMessage());
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
